import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  Card,
  Button,
  Input,
  Table,
  Modal,
  Form,
  message,
  Tooltip,
  Space,
  Pagination,
} from "antd";
import {
  ArrowLeftOutlined,
  EditOutlined,
  QuestionCircleOutlined,
  EyeOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import styles from "./Profile.module.scss";

import { User, ChatHistoryRecord, ChatMessage } from "../../types/index";
import { renewVIP, setNickname, getUserInfo } from "../../services/user";
import { getAIHistory, deleteAIHistory } from "../../services/chat";

import { useChatHistoryStore } from "../../context/index";

const Profile = () => {
  const setSelectedHistory = useChatHistoryStore(
    (state) => state.setSelectedHistory
  );

  // 使用 message 的 hook API 确保消息能正确显示
  const [messageApi, contextHolder] = message.useMessage();

  const navigate = useNavigate();
  const [isEditNameModalVisible, setIsEditNameModalVisible] = useState(false);

  // 统一管理用户信息
  const [userInfo, setUserInfo] = useState<User>({
    username: "", // 手机号
    nickname: "",
    VIPExpire: "",
  });

  const [newNickname, setNewNickname] = useState("");
  const [redeemCode, setRedeemCode] = useState("");
  const [loading, setLoading] = useState(false);
  const [recordsLoading, setRecordsLoading] = useState(true);
  const [records, setRecords] = useState<ChatHistoryRecord[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 加载用户信息
  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const response = await getUserInfo();
        setUserInfo(response);
      } catch (error) {
        console.error("获取用户信息失败:", error);
        messageApi.error("获取用户信息失败");
      }
    };

    fetchUserInfo();
  }, [messageApi]);

  // 加载生成记录数据
  useEffect(() => {
    const fetchRecords = async () => {
      setRecordsLoading(true);
      try {
        const response = await getAIHistory(
          pagination.current,
          pagination.pageSize
        );
        setRecords(
          response.results.map((item) => ({
            key: `${item.id}`,
            id: item.id,
            time: item.timestamp,
            agentType: "agentType",
            agentTopic: "agentTopic",
            userPrompt: "userPrompt",
            history: (JSON.parse(item.history) || []) as ChatMessage[],
            timestamp: item.timestamp,
            AIGroup: item.AIGroup,
            AIName: item.AIName,
          }))
        );
        setPagination({
          ...pagination,
          total: response.totalCount,
        });
      } catch (error) {
        console.error("获取历史记录失败:", error);
        messageApi.error("获取历史记录失败");
      } finally {
        setRecordsLoading(false);
      }
    };

    fetchRecords();
  }, [pagination.current, pagination.pageSize, messageApi]);

  // 处理分页变化
  const handleTableChange = (page: number, pageSize?: number) => {
    setPagination({
      ...pagination,
      current: page,
      pageSize: pageSize || pagination.pageSize,
    });
  };

  // 处理用户昵称修改
  const handleEditNickname = () => {
    setNewNickname(userInfo.nickname || "");
    setIsEditNameModalVisible(true);
  };

  const handleSaveNickname = async () => {
    if (!newNickname.trim()) {
      messageApi.error("昵称不能为空");
      return;
    }

    try {
      setLoading(true);
      await setNickname({ nickname: newNickname });

      // 更新本地状态
      setUserInfo({
        ...userInfo,
        nickname: newNickname,
      });

      messageApi.success("昵称修改成功");
      setIsEditNameModalVisible(false);
    } catch (error) {
      console.error("修改昵称失败:", error);
      messageApi.error("修改昵称失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  // 处理会员兑换码
  // A0000001~A0000010，30天的，B0000001~A0000010，365天的
  const handleRedeemCode = async () => {
    if (!redeemCode.trim()) {
      messageApi.error("请输入兑换码");
      return;
    }

    try {
      setLoading(true);
      const response = await renewVIP({ redeemcode: redeemCode });
      messageApi.success(`兑换成功！${response.message}`);
      setRedeemCode("");

      // 刷新用户信息以获取最新的VIP到期时间
      const updatedUserInfo = await getUserInfo();
      setUserInfo(updatedUserInfo);
    } catch (error) {
      console.error("兑换失败:", error);
      messageApi.error("兑换失败，无效的兑换码");
    } finally {
      setLoading(false);
    }
  };

  // 处理查看记录
  const handleViewRecord = (record: ChatHistoryRecord) => {
    setSelectedHistory(record);
    // 实际应用中可能需要导航到详情页或打开对话框
    navigate(`/chat/${record.id}`);
  };

  // 处理删除记录
  const handleDeleteRecord = async (record: ChatHistoryRecord) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这条生成记录吗？此操作不可恢复。",
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          await deleteAIHistory(record.id);
          setRecords(records.filter((item) => item.key !== record.key));
          messageApi.success("记录已删除");
        } catch (error) {
          console.error("删除记录失败:", error);
          messageApi.error("删除记录失败，请重试");
        }
      },
    });
  };

  // 格式化手机号显示
  const formatPhoneNumber = (phone: string) => {
    if (!phone || !phone.match(/\d{11}/)) return "未绑定手机号";
    return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
  };

  // 表格列定义
  const columns: ColumnsType<ChatHistoryRecord> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: "12%",
      align: "center", // 左对齐
    },
    {
      title: "生成时间",
      dataIndex: "time",
      key: "time",
      width: "22%", // 使用百分比宽度实现自适应
      align: "center",
    },
    {
      title: "智能体分类",
      dataIndex: "AIGroup",
      key: "AIGroup",
      width: "22%",
      align: "left",
    },
    {
      title: "智能体主题",
      dataIndex: "AIName",
      key: "AIName",
      width: "22%",
      align: "left",
    },
    // {
    //   title: "用户提示词",
    //   dataIndex: "userPrompt",
    //   key: "userPrompt",
    //   ellipsis: true,
    //   align: "left",
    // },
    {
      title: "操作",
      key: "action",
      width: "22%",
      align: "center",
      render: (_, record) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewRecord(record)}
          >
            查看
          </Button>
          <Button
            type="text"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteRecord(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className={styles.profileContainer}>
      {/* 添加 message 容器 */}
      {contextHolder}

      {/* 标题栏 */}
      <div className={styles.titleBar}>
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          className={styles.backButton}
        />
        <h1 className={styles.title}>个人中心</h1>
      </div>

      {/* 用户信息卡片 */}
      <Card className={styles.infoCard}>
        {/* 用户昵称 */}
        <div className={styles.infoItem}>
          <span className={styles.infoLabel}>用户昵称：</span>
          <span className={styles.infoValue}>
            {userInfo.nickname || "未设置"}
          </span>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={handleEditNickname}
            className={styles.actionButton}
          >
            修改
          </Button>
        </div>

        {/* 手机号 */}
        <div className={styles.infoItem}>
          <span className={styles.infoLabel}>手机号：</span>
          <span className={styles.infoValue}>
            {formatPhoneNumber(userInfo.username)}
          </span>
          <Tooltip title="如需修改手机号，请联系客服">
            <Button
              type="link"
              icon={<QuestionCircleOutlined />}
              className={styles.actionButton}
            >
              请联系客服修改
            </Button>
          </Tooltip>
        </div>

        {/* 会员到期时间 */}
        <div className={styles.infoItem}>
          <span className={styles.infoLabel}>会员到期时间：</span>
          <span className={styles.infoValue}>
            {userInfo.VIPExpire || "加载中..."}
          </span>
        </div>

        {/* 会员兑换 */}
        <div className={styles.infoItem}>
          <span className={styles.infoLabel}>会员兑换（请联系客服获取）：</span>
          <Input
            placeholder="请输入兑换码"
            value={redeemCode}
            onChange={(e) => setRedeemCode(e.target.value)}
            className={styles.redeemInput}
          />
          <Button
            type="primary"
            onClick={handleRedeemCode}
            loading={loading}
            className={styles.redeemButton}
          >
            确认兑换
          </Button>
        </div>
      </Card>

      {/* 生成记录 */}
      <div className={styles.recordsSection}>
        <h2 className={styles.sectionTitle}>生成记录：</h2>

        <div className={styles.recordsTable}>
          <Table
            columns={columns}
            dataSource={records}
            loading={recordsLoading}
            pagination={false}
            tableLayout="fixed"
            size="middle"
            bordered={false}
          />
        </div>

        {/* 分页器 */}
        <div className={styles.paginationContainer}>
          <span className={styles.paginationInfo}>
            每页{pagination.pageSize}条 共 {pagination.total}条记录
          </span>
          <Pagination
            current={pagination.current}
            pageSize={pagination.pageSize}
            total={pagination.total}
            onChange={handleTableChange}
            showSizeChanger={false}
          />
        </div>
      </div>

      {/* 修改用户昵称弹窗 */}
      <Modal
        title="修改昵称"
        open={isEditNameModalVisible}
        onOk={handleSaveNickname}
        onCancel={() => setIsEditNameModalVisible(false)}
        okText="保存"
        cancelText="取消"
        confirmLoading={loading}
      >
        <Form layout="vertical">
          <Form.Item
            label="新昵称"
            rules={[{ required: true, message: "请输入新昵称" }]}
          >
            <Input
              value={newNickname}
              onChange={(e) => setNewNickname(e.target.value)}
              placeholder="请输入新昵称"
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Profile;
